﻿using System.Linq;
using Sausage.Common;
using Sausage.Web.DataModel;

namespace Sausage.Web.Domain
{
    public enum LoginResult
    {
        Ok = 0,
        UserDisabled = -1,
        UserPasswordNotMatch = -2,
        UserNotExist = -3,
        MustChangePassword = -4
    }

    public class LoginHelper
    {
        /// <summary>
        /// 执行用户登录操作。
        /// </summary>
        /// <param name="loginName">用户的登录名。</param>
        /// <param name="password">用户的登录密码。</param>
        /// <param name="user">用于返回登录用户的用户信息。</param>
        /// <returns>登录结果。</returns>
        /// <remarks></remarks>
        public static LoginResult Login(string loginName, string password, out User user)
        {
            user = UserHelper.GetUserByLoginName(loginName);
            if (user != null)
            {
                if (PasswordHash.Compare(password, user.Password))
                {
                    if (!user.IsEnabled)
                        return LoginResult.UserDisabled;

                    if (user.MustChangePassword)
                        return LoginResult.MustChangePassword;

                    UserHelper.UserLastLogin(user);
                    return LoginResult.Ok;
                }
                return LoginResult.UserPasswordNotMatch;
            }
            return LoginResult.UserNotExist;
        }
    }
}
